package com.jxj.daoImpl;

import javax.annotation.Resource;
import javax.persistence.Id;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.criteria.internal.expression.function.AggregationFunction.COUNT;
import org.springframework.stereotype.Repository;
import com.jxj.entity.Demand;
import com.jxj.entity.Receive;
import com.jxj.entity.User;







@Repository
public class HelpDaoImpl {
	@Resource
	private SessionFactory sessionFactory;
	public Session getSession()
    {
        return sessionFactory.getCurrentSession();
    }
	//添加需求
	public void addDemand(User user,Demand demand,String xuehao,double price){	
		demand.setContent(demand.getContent());
		demand.setPeople(demand.getPeople());
		demand.setType(demand.getType());
		demand.setPrice(demand.getPrice());	
		demand.setUser(user);
		String hql="select money from User where xuehao=?";
		double money=(double) this.getSession().createQuery(hql).setParameter(0, xuehao).uniqueResult();
		if(money<price && money>0){
			System.out.println("钱不够");
		}
		String hql1="update User set money=money-? where xuehao=?";
		this.getSession().createQuery(hql1).setParameter(0, price).setParameter(1, xuehao).executeUpdate();
		getSession().save(demand);
	}	
	
	
	public List<Demand> findAll(int pageNum, int pageSize){
		String hql="from Demand";
		Query query = getSession().createQuery(hql);
		query.setFirstResult((pageNum-1)*pageSize);
		query.setMaxResults(pageSize);	
		List<Demand> list=(List<Demand>) query.list();
		return list;
	}
/*	public boolean findId(int id){
		String hql="from Demand where id=?";
		Query query=getSession().createQuery(hql);
		query.setParameter(0, id);			
		query.uniqueResult();
		if(query.uniqueResult()!=null){
			return true;
		}
		return false;
		
	}*/
	
	public void updateAccept(Demand demand){				
		demand=getSession().load(Demand.class, demand.getId());
		demand.setAccept(true);		
		getSession().update(demand);				
	}
	public void addRecive(User user,Demand demand,Receive receive/*,String xuehao,double price*/){	
		/*String hql="select money from User where xuehao=?";
		double money=(double) this.getSession().createQuery(hql).setParameter(0, xuehao).uniqueResult();

		String hql1="update User set money=money+? where xuehao=?";
		this.getSession().createQuery(hql1).setParameter(0, price).setParameter(1, xuehao).executeUpdate();*/
		receive.setUser(user);
		receive.setDemand(demand);
		receive.setFinish("未完成");
		getSession().save(receive);		
	}
	public boolean findUdid(int did ){			
		String hql="from Receive where did=?";
		Query query=getSession().createQuery(hql);		
		query.setParameter(0,did);
		query.uniqueResult();		
		if(query.uniqueResult() == null){			
			return true;			
		}			
		else {
			return false;
		}
		
	}

}
